import React, { useEffect, useState } from "react";
import { Modal, Input, Button, Avatar, message, List, Tooltip, Space } from "antd";
import { LikeOutlined, LikeFilled } from "@ant-design/icons";
import {
  postDoComment,
  showMoodPostComment,
  queryMoodPostCommentId,
  // 假设有评论点赞接口 postDoCommentThumb
} from "@/api/moodPostController";

interface CommentModalProps {
  visible: boolean;
  postId: number | null;
  onClose: () => void;
}

interface CommentItem {
  id: number;
  postId: number;
  userId: number;
  userAccount: string;
  userAvatar: string;
  remarks: string;
  direction?: string;
  comment: string;
  parentId: number | null;
  replyUserId?: number;
  replyAccount?: string;
  likeNum?: number;
  createTime?: string;
  children?: CommentItem[];
}

const CommentModal: React.FC<CommentModalProps> = ({ visible, postId, onClose }) => {
  const [commentList, setCommentList] = useState<CommentItem[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [replyTo, setReplyTo] = useState<{ parentId: number | null; replyUserId?: number; replyAccount?: string } | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // 获取当前登录用户信息（根据你的项目实际情况获取）
  const currentUser = {
    userId: 1, // TODO: 替换为实际登录用户id
    userAccount: "testuser", // TODO: 替换为实际登录用户账号
  };

  // 获取评论列表
  const fetchComments = async () => {
    if (!postId) return;
    setLoading(true);
    try {
      const res = await showMoodPostComment({ postId });
      if (res.code === 0 && Array.isArray(res.data)) {
        // 处理为树形结构
        const list: CommentItem[] = res.data;
        const map: { [key: number]: CommentItem } = {};
        const roots: CommentItem[] = [];
        list.forEach(item => {
          map[item.id] = { ...item, children: [] };
        });
        list.forEach(item => {
          if (!item.parentId || item.parentId === 0) {
            roots.push(map[item.id]);
          } else if (map[item.parentId]) {
            map[item.parentId].children!.push(map[item.id]);
          }
        });
        setCommentList(roots);
      } else {
        setCommentList([]);
      }
    } catch {
      setCommentList([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible && postId) {
      fetchComments();
      setInputValue("");
      setReplyTo(null);
    }
  }, [visible, postId]);

  // 发表评论
  const handleSubmit = async () => {
    if (!inputValue.trim()) {
      message.warning("请输入评论内容");
      return;
    }
    if (!postId) return;
    setSubmitting(true);
    try {
      let parentId = 0;
      let replyUserId = undefined;
      let replyAccount = undefined;
      if (replyTo && replyTo.parentId) {
        // 二级评论，需查 parentId
        const res = await queryMoodPostCommentId({
          postId,
          userId: replyTo.replyUserId,
        });
        if (res.code === 0 && res.data) {
          parentId = res.data.id;
          replyUserId = replyTo.replyUserId;
          replyAccount = replyTo.replyAccount;
        }
      }
      const params = {
        postId,
        comment: inputValue,
        parentId: parentId || 0,
        replyUserId: replyUserId || undefined,
        replyAccount: replyAccount || undefined,
      };
      const res = await postDoComment(params);
      if (res.code === 0) {
        message.success("评论成功");
        setInputValue("");
        setReplyTo(null);
        fetchComments();
      } else {
        message.error(res.message || "评论失败");
      }
    } catch {
      message.error("评论失败");
    } finally {
      setSubmitting(false);
    }
  };

  // 回复评论
  const handleReply = (item: CommentItem) => {
    setReplyTo({
      parentId: item.id,
      replyUserId: item.userId,
      replyAccount: item.userAccount,
    });
    setInputValue(`@${item.remarks || item.userAccount} `);
  };

  // 点赞评论（如有接口可补充）
  const handleLike = (item: CommentItem) => {
    message.info("点赞功能待实现");
  };

  // 渲染评论项
  const renderCommentItem = (item: CommentItem, isChild = false) => (
    <div
      key={item.id}
      style={{
        display: "flex",
        alignItems: "flex-start",
        marginBottom: isChild ? 12 : 20,
        marginLeft: isChild ? 48 : 0,
      }}
    >
      <Avatar src={item.userAvatar} size={36} style={{ marginRight: 12 }} />
      <div style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center" }}>
          <span style={{ fontWeight: 500, fontSize: 15 }}>{item.remarks || item.userAccount}</span>
          {!isChild && item.direction && (
            <span style={{ marginLeft: 8, color: "#888", fontSize: 13 }}>{item.direction}</span>
          )}
        </div>
        <div style={{ fontSize: 15, color: "#222", margin: "4px 0" }}>{item.comment}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 16, fontSize: 13, color: "#888" }}>
          <span>{item.createTime}</span>
          <span style={{ cursor: "pointer" }} onClick={() => handleLike(item)}>
            <LikeOutlined style={{ marginRight: 4 }} />{item.likeNum || 0}
          </span>
          <span style={{ cursor: "pointer" }} onClick={() => handleReply(item)}>
            {isChild ? "回复" : "评论"}
          </span>
        </div>
        {/* 二级评论 */}
        {item.children && item.children.length > 0 && (
          <div style={{ marginTop: 8 }}>
            {item.children.map(child => renderCommentItem(child, true))}
          </div>
        )}
      </div>
    </div>
  );

  return (
    <Modal
      open={visible}
      onCancel={onClose}
      footer={null}
      title={null}
      width={600}
      bodyStyle={{ padding: 0, borderRadius: 8, background: "#fff" }}
      style={{ top: 80 }}
      destroyOnClose
    >
      <div style={{ padding: 24, paddingBottom: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 12 }}>评论 {commentList.length}</div>
        <div style={{ border: "1px solid #f0f0f0", borderRadius: 8, padding: 16, minHeight: 120, maxHeight: 320, overflowY: "auto", background: "#fafbfc" }}>
          {commentList.length === 0 ? (
            <div style={{ color: "#888", textAlign: "center", marginTop: 40 }}>暂无评论，快来抢沙发吧~</div>
          ) : (
            commentList.map(item => renderCommentItem(item))
          )}
        </div>
        <div style={{ marginTop: 16, borderTop: "1px solid #f0f0f0", paddingTop: 16 }}>
          <Input.TextArea
            value={inputValue}
            onChange={e => setInputValue(e.target.value)}
            placeholder={replyTo ? `回复 @${replyTo.replyAccount}：` : "友善表达，友善交流"}
            autoSize={{ minRows: 2, maxRows: 4 }}
            maxLength={1000}
            style={{ marginBottom: 8 }}
          />
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <Button type="primary" onClick={handleSubmit} loading={submitting}>
              发送
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default CommentModal; 